// / * 路由拦截 未登录用户不能访问某些页面 */
import { useUserStore } from '@/stores/user.js'
// 页面白名单，不受拦截
const white = [
  '/pages/index/index',
  '/pages/classify/classify',
  '/pages/shop/shop',
  '/pages/loginAndRegister/loginAndRegister',
  '/pages/mine/mine',
  '/pages/dessertDetail/dessertDetail',
  '/pages/diyDessert/diyDessert',
]
export default async function interceptor() {
  const userStore = useUserStore()
  // 遍历路由跳转方式 添加拦截器
  let list = ['navigateTo', 'redirectTo', 'relaunch', 'switchTab']
  list.forEach((item) => {
    uni.addInterceptor(item, {
      invoke(e) {
        // 获取要跳转到页面路径 url去掉“?”以及后面参数
        let url = e.url.split('?')[0]
        let notNeed = white.includes(url)
        // 如果在白名单内则不需要登录
        if (notNeed) {
          return e
        } else {
          if (Object.keys(userStore.userInfo).length <= 0) {
            uni.showModal({
              title: '温馨提示',
              content: '您还未登录，请先登录',
              success: (res) => {
                if (res.confirm) {
                  uni.navigateTo({
                    url: '/pages/loginAndRegister/loginAndRegister',
                  })
                }
              },
            })
            return false
          } else {
            return e
          }
        }
      },
      fail: (err) => {
        console.log(err)
      },
    })
  })
}
